package com.yzkj.cpjxc.business.service.impl;

import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.IDUtils;
import com.yzkj.cpjxc.business.constants.SecurityMgrConstants;
import com.yzkj.cpjxc.business.constants.SysRoleConstants;
import com.yzkj.cpjxc.business.domain.SysRole;
import com.yzkj.cpjxc.business.domain.SysRoleQueryVo;
import com.yzkj.cpjxc.business.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统角色 Service 实现
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

	public Logger log = Logger.getLogger(SysRoleServiceImpl.class);

	/**
	 * MyBatis 命名空间
	 */
	private final static String MAPPER_NAMESPACE = "com.chkj.sysMgr.securityMgr.sysRole.mappers.SysRoleMapper";

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	@Override
	public BusinessMap create(SysRole sr) throws Exception {
		BusinessMap bm = new BusinessMap();
		//1、判断角色是否存在
		if (this.isExists(sr)) {
			bm.put(Constants.WARNING_MSG, SysRoleConstants.ROLENAME_EXISTS);
			return bm;
		}
		//2、保存角色
		if (StringUtils.isBlank(sr.getRoleId())) {
			sr.setRoleId(IDUtils.genUUID());
		}
		sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".add", sr);
		return bm;
	}

	@Override
	public boolean isExists(SysRole sysRole) throws Exception {
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isExists", sysRole) > 0;
	}

	@Override
	public SysRole getById(String sysRoleId) throws Exception {
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getById", sysRoleId);
	}

	@Override
	public BusinessMap edit(SysRole sysRole) throws Exception {
		BusinessMap bm = new BusinessMap();

		// 不能修改超级管理员角色名称
		SysRole sr = this.getById(sysRole.getRoleId());
		if (sr != null) {
			if (Constants.ADMIN.equals(sr.getRoleName()) && !Constants.ADMIN.equals(sysRole.getRoleName())) {
				bm.put(Constants.WARNING_MSG, "无权限修改超级管理员角色名称！");
				return bm;
			}
		}

		// 判断角色是否存在
		if (this.isExists(sysRole)) {
			bm.put(Constants.WARNING_MSG, SysRoleConstants.ROLENAME_EXISTS);
			return bm;
		}
		sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".edit", sysRole);
		return bm;
	}

	@Override
	public BusinessMap delete(String sysRoleId) throws Exception {
		BusinessMap bm = new BusinessMap();

		//超级管理员角色不能删除
		SysRole sr = this.getById(sysRoleId);
		if (sr != null) {
			if (Constants.ADMIN.equals(sr.getRoleName())) {
				bm.put(Constants.ERROR_MSG, "无权限删除超级管理员角色！");
				return bm;
			}
		}

		// 物理删除角色
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".deleteById", sysRoleId);
		// 物理删除角色与用户的关系
		sqlSessionTemplate.delete(SecurityMgrConstants.USER_ROLE_MAPPER_NAMESPACE + ".deleteByRoleId", sysRoleId);
		// 物理删除角色与权限的关系
		sqlSessionTemplate.delete(SecurityMgrConstants.ROLE_AUTHORITY_MAPPER_NAMESPACE + ".deleteByRoleId", sysRoleId);
		
		return bm;
	}

	@Override
	public Pager<SysRole> search(Pager<SysRole> pager, SysRoleQueryVo queryVo) throws Exception {
		//1、添加查询额外查询条件
		List<SysRole> list = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".page", queryVo, new RowBounds((pager.getCurrentPage() - 1) * pager.getLimit(), pager.getLimit()));
		pager.setDataList(list);

		Long total = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getTotal", queryVo);
		pager.setTotal(total);
		return pager;
	}

	@Override
	public SysRole getRoleByRoleName(String roleName) throws Exception {
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getByRoleName", roleName);
	}

	@Override
	public List<SysRole> getSysRolesByUserId(String userId) throws Exception {
		return sqlSessionTemplate.selectList(SecurityMgrConstants.USER_ROLE_MAPPER_NAMESPACE + ".getSysRolesByUserId", userId);
	}

	@Override
	public void setAuthority(String roleId, String authorityIds) throws Exception {
		//删除角色和权限的所有旧关联
		sqlSessionTemplate.delete(SecurityMgrConstants.ROLE_AUTHORITY_MAPPER_NAMESPACE + ".deleteByRoleId", roleId);

		//建立起角色和权限新的关联
		if (StringUtils.isNotBlank(authorityIds)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("roleId", roleId);
			map.put("authorityIds", authorityIds.split(","));
			sqlSessionTemplate.insert(SecurityMgrConstants.ROLE_AUTHORITY_MAPPER_NAMESPACE + ".batchAdd", map);
		}
	}

	@Override
	public void initData() throws Exception {
		SysRole sr = this.getRoleByRoleName(Constants.ADMIN);
		if (sr == null) {
			SysRole admin = new SysRole();
			admin.setRoleId(IDUtils.genUUID());
			admin.setRoleName(Constants.ADMIN);
			admin.setStatus(Constants.STATUS_ACTIVE);
			admin.setRemark("超级管理员角色");

			log.info("初始化管理员角色-------------------------------------------------------------------------------------");
			this.create(admin);
		}
	}

}
